package kn.xianSubway.service.impl;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.volcengine.ark.runtime.model.bot.completion.chat.BotChatCompletionRequest;
import com.volcengine.ark.runtime.model.bot.completion.chat.BotChatCompletionResult;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import kn.xianSubway.common.OkHttpUtils;
import kn.xianSubway.entity.MonitorReqAiRecord;
import kn.xianSubway.mapper.MonitorReqAiRecordMapper;
import kn.xianSubway.service.ExternalService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import okhttp3.FormBody;
import okhttp3.Headers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class ExternalServiceImpl implements ExternalService {

    @Autowired
    private MonitorReqAiRecordMapper monitorReqAiRecordMapper;

    @Override
    public String queryTonalState(kn.xianSubway.req.QueryTonalStateReq req, String nextUrl) {


        Headers.Builder headersBuilder = new Headers.Builder();
        headersBuilder.add("Content-Type", "application/x-www-form-urlencoded");

        FormBody.Builder formBuilder = OkHttpUtils.formBodyBuilder()
                .add("title", JSONUtil.toJsonStr(req.getTitle()))
                .add("content", JSONUtil.toJsonStr(req.getContent()));
        try {
            log.info("调性请求地址：{}",nextUrl);
            String body = OkHttpUtils.postFormWithHeaders(nextUrl, formBuilder, headersBuilder);
            JSONObject obj = JSONUtil.parseObj(body);
            String label = (String) obj.get("label");
            switch (label){
                case "__label__positive":
                    return "0";
                case "__label__unrelated":
                case "__label__neutral":
                    return "1";
                case "__label__negative":
                    return "2";
                default:
                    return "1";
            }
        } catch (Exception e) {
            log.error("调性判断出错：{},异常信息{}",req, e.getMessage());
            e.printStackTrace();
        }
        return "1";
    }

    static String apiKey = "e0c50719-80ee-46c9-bb57-9fb267b4b6fe";
    static ConnectionPool connectionPool = new ConnectionPool(50, 10, TimeUnit.SECONDS);
    static Dispatcher dispatcher = new Dispatcher();
    static {
        dispatcher.setMaxRequests(100);
        dispatcher.setMaxRequestsPerHost(50);
    }

    static ArkService service = ArkService.builder().dispatcher(dispatcher).connectionPool(connectionPool).baseUrl("https://ark.cn-beijing.volces.com/api/v3/").apiKey(apiKey).build();

    // 只在程序退出时关闭线程池
    static {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> service.shutdownExecutor()));
    }
    @Override
    public Map<String,String> queryNewTonalState(String context, String website, String model1, String model2) {

        String model = model1;
        log.info("\n----- standard request -----");

        int maxRetries = 5;  // 最多重试 3 次
        int attempt = 0;      // 当前重试次数

        while (attempt < maxRetries) {
            try {
                attempt++;
                long start = System.currentTimeMillis();

                final List<ChatMessage> messages = new ArrayList<>();
                messages.add(ChatMessage.builder()
                        .role(ChatMessageRole.SYSTEM)
                        .content("你是豆包，是由字节跳动开发的 AI 人工智能助手")
                        .build());
                messages.add(ChatMessage.builder()
                        .role(ChatMessageRole.USER)
                        .content(context)
                        .build());

                BotChatCompletionRequest chatCompletionRequest = BotChatCompletionRequest.builder()
                        .model(model)
                        .messages(messages)
                        .build();

                BotChatCompletionResult chatCompletionResult = service.createBotChatCompletion(chatCompletionRequest);
                List<String> results = new ArrayList<>();
                chatCompletionResult.getChoices().forEach(choice -> results.add(String.valueOf(choice.getMessage().getContent())));
                long endTime = System.currentTimeMillis();
                long time = endTime - start;
                log.info("第 {} 次链接 {}尝试调用 AI 接口...，耗时{}ms", attempt,website,time);
                MonitorReqAiRecord monitorReqAiRecord = new MonitorReqAiRecord();
                monitorReqAiRecord.setReq(context);
                monitorReqAiRecord.setResp(results.toString());
                monitorReqAiRecord.setTime((int) time);
                monitorReqAiRecord.setWebsite(website);
                monitorReqAiRecordMapper.insert(monitorReqAiRecord);
                Map<String,String> resultMap = new HashMap<>();
                String result = results.get(0);
                String[] lines = result.split("\n");
                for (String line : lines) {
                    String[] parts = line.split(":");
                    String key = parts[0];
                    String value = parts[1];
                    // 将处理后的键值对存入 map
                    resultMap.put(key.trim(), value.trim());

                }
                return resultMap;
                 // **成功返回，终止循环**
            } catch (Exception e) {
                log.error("调用 AI 接口失败，第 {} 次重试，错误信息: {}", attempt, e.getMessage());
                // 备用
                if(attempt >= 3){
                    model = model2;
                }

                if (attempt >= maxRetries) {
                    log.error("已达到最大重试次数({})，请求终止。", maxRetries);
                    break;
                }

                try {
                    TimeUnit.MILLISECONDS.sleep(500);  // **重试前等待 500ms，避免高频失败**
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    log.error("线程等待时发生中断异常: {}", ie.getMessage());
                }
            }
        }
        return new HashMap<>();
    }

    public static void main(String[] args) {
        ArrayList<String> objects = new ArrayList<>();
        objects.add("相关");
        Map<String,String> resultMap = new HashMap<>();

        String[] lines = objects.toString().split("\n");
        for (String line : lines) {
            String[] parts = line.split(":");
            String key = parts[0];
            String value = parts[1];
            // 将处理后的键值对存入 map
            resultMap.put(key.trim(), value.trim());

        }
    }
}
